package com.spring.future.modules.sys.security;

import com.spring.future.common.utils.Const;
import com.spring.future.common.utils.ThreadLocalContext;
import com.spring.future.modules.sys.domain.Account;
import com.spring.future.modules.sys.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Collection;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;

/**
 * Created by liuj on 2016-07-25.
 */

@Service("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired
    private AccountService accountService;
    @Autowired
    private HttpSession httpSession;

    @Override
    public UserDetails loadUserByUsername(String loginName) throws UsernameNotFoundException {
        Account account = accountService.findByLoginName(loginName);
        boolean enabled = true;
        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;
        boolean accountNonLocked = true;
        UserDetails userDetails = new CustomUserDetails(
                account.getUserName(),
                account.getPassword(),
                enabled,
                accountNonExpired,
                credentialsNonExpired,
                accountNonLocked,
                getAuthorities(account),
                account);
        return userDetails;
    }

    /**
     * Retrieves a collection of {@link GrantedAuthority} based on a list of
     * roles
     *
     * @param account
     *            the assigned roles of the account
     * @return a collection of {@link GrantedAuthority}
     */
    private Collection<? extends GrantedAuthority> getAuthorities(Account account) {
        Set<SimpleGrantedAuthority> authList = new TreeSet<SimpleGrantedAuthority>(new SimpleGrantedAuthorityComparator());
        return authList;
    }


    private static class SimpleGrantedAuthorityComparator implements Comparator<SimpleGrantedAuthority> {
        @Override
        public int compare(SimpleGrantedAuthority o1, SimpleGrantedAuthority o2) {
            return o1.equals(o2) ? 0 : -1;
        }
    }

}
